package com.xcc.core.netty.memery;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;




/**
 * 
 * 内存映射文件 管理到内存级别，不进行文件读写
 * 
 * @author xcc
 *
 */
public class MemeryUtils {

	public static MappedByteBuffer mapBuffer;
	static {
		try {
			int length = 0x8FFFFFF;//一个byte占1B，所以共向文件中存128M的数据
			FileChannel	channel = FileChannel.open(Paths.get("memery.txt"),
					StandardOpenOption.READ,
					StandardOpenOption.WRITE);
		// 	 mapBuffer = channel.map(FileChannel.MapMode.PRIVATE, 0, 1024);
			mapBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1024);

		} catch (IOException e) {
			e.printStackTrace();
		}  
	}


	public  static String   getMemmery(byte[] bs) {
	/*	CharBuffer charBuffer = null;
		try {
			Charset charset = Charset.defaultCharset();
			CharsetDecoder decoder = charset.newDecoder();
			charBuffer = decoder.decode(mapBuffer);
		} catch (CharacterCodingException e) {
			e.printStackTrace();
		}*/
		for(int i=0;i<mapBuffer.limit();i++) {
			bs[i]=mapBuffer.get(i);
		}
		return  new String(bs);
	}

	public static void setMap(byte[] bs) {
		mapBuffer.put(bs);
	}

	public static MappedByteBuffer getMap() {
		return mapBuffer;
	}




}
